package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.entity.Order;
import com.itheima.entity.Product;
import com.itheima.api.ProductServiceApi;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private DiscoveryClient discoveryClient;

    //商品服务api
    @Autowired
    private ProductServiceApi productServiceApi;

    //准备买1件商品
    @GetMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", pid);//调用商品微服务,查询商品信息
        //从nacos中获取服务地址
        //自定义规则实现随机挑选服务
        /*List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        int index = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(index);
        String url = serviceInstance.getHost() + ":" +
                serviceInstance.getPort();
        log.info(">>从nacos中获取到的微服务地址为:" + url);*/

        //通过restTemplate调用商品微服务
        /*String url = "service-product";
        Product product = restTemplate.getForObject(
                "http://" + url + "/product/" + pid, Product.class);*/

        //通过feign 调用商品服务接口
        Product product = productServiceApi.findByPid(pid);
        log.info(">>商品信息，查询结果:" + JSON.toJSONString(product));

        //模拟一次网络延时
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(product.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        //orderService.save(order);
        return order;
    }

    @RequestMapping("/order/message")
    public String message() {
        return "高并发下的问题测试";
    }
}
